package fnic.prehand.action;

import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.NCSARequestLog;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.thread.QueuedThreadPool;

import fnic.jsontrans.AgentUrl;
import fnic.prehand.common.AgentConfig;
import fnic.prehand.common.BlockQueueService;


public class ESClientHttpServer implements Runnable{
	private static final AgentConfig config = AgentConfig.getInstance();
	private static Logger LOG = Logger.getLogger(ESClientHttpServer.class); 
	private StateGridServlet stateGridSer = new StateGridServlet();
	private StateGridStatisticServlet stateGridStaSer = new StateGridStatisticServlet();
	
//	private final int serverPort;
//	private final String logName;
//	private final String skurl;
//	private final String cindex;
//	private final String ctype;
//	private final BlockQueueService queue;
	
	/*
	 * 功能：mujob和netcenter的构造函数
	 * 参数：
	 *     serverport  端口标示
	 *     logname     日志文件名
	 */
//	public ESClientHttpServer(int serverport, String logname, String skUrl, String idx, String type, BlockQueueService queue){
//		this.serverPort = serverport;
//		this.logName = logname;
//		this.skurl = skUrl;
//		this.cindex = idx;
//		this.ctype = type;
//		this.queue = queue;
//	}
	
//	public ESClientHttpServer(BlockQueueService queue){
//		this.queue = queue;
//	}
	
	private void createActiveServer(int serverPort, String logName, String cindex, String ctype, String ctlurl, String skUrl){
		BlockQueueService queue = new BlockQueueService();
		QueuedThreadPool threadPool = new QueuedThreadPool(
				config.getMaxThreadNumOfQueue(),
				config.getMinThreadNumOfQueue());
		Server server = new Server(threadPool);
		HttpConfiguration httpConfig = new HttpConfiguration();
		httpConfig.setSecureScheme("https");
		ServerConnector httpConnector = new ServerConnector(server,
				new HttpConnectionFactory(httpConfig));
		httpConnector.setPort(serverPort);
		httpConnector.setIdleTimeout(config.getIdleTimeout());
		server.addConnector(httpConnector);

		HandlerCollection handlers = new HandlerCollection();
		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
		context.setContextPath("/");
		context.addServlet(new ServletHolder(new HttpGatherServlet(cindex, ctype, ctlurl,skUrl, queue)), AgentUrl.PROBETASK);
		HttpServlet simpleSearch = new SearchFromESServlet(cindex, ctype);
		context.addServlet(new ServletHolder(simpleSearch), AgentUrl.WebToES);
		context.addServlet(new ServletHolder(simpleSearch),AgentUrl.MOBILE_SEARCH);
		context.addServlet(new ServletHolder(new ModeSearchServlet(cindex,ctype)), AgentUrl.TEMPLATE_SEARCH);
		context.addServlet(new ServletHolder(stateGridSer), AgentUrl.PERFORMANCEANALYSIS);
		context.addServlet(new ServletHolder(stateGridStaSer), AgentUrl.STATISTICS_SEARCH);
		handlers.addHandler(context);
		server.setHandler(handlers);

		// request log
		NCSARequestLog requestLog = new NCSARequestLog();
		requestLog.setFilename(logName);
		requestLog.setRetainDays(config.getRetainDays());
		requestLog.setLogTimeZone(config.getRequestLogTimezone());
		requestLog.setLogDateFormat(config.getRequestLogDateFormat());
		requestLog.setAppend(true);
		requestLog.setExtended(true);
		RequestLogHandler handlerReqLog = new RequestLogHandler();
		handlerReqLog.setRequestLog(requestLog);
		handlers.addHandler(handlerReqLog);

//		Thread localRiverThd = new Thread(new ActiveLocalQueueRiver(cindex, ctype, ctlurl, skUrl, queue));
//		localRiverThd.start();
		
		try {
			server.start();
		} catch (Exception e) {
			LOG.error("server exception! - " + e.getMessage());
		}
	}
	
	private void createApServer(int serverPort, String logName){
		QueuedThreadPool threadPool = new QueuedThreadPool(
				config.getMaxThreadNumOfQueue(),
				config.getMinThreadNumOfQueue());
		Server server = new Server(threadPool);
		HttpConfiguration httpConfig = new HttpConfiguration();
		httpConfig.setSecureScheme("https");
		ServerConnector httpConnector = new ServerConnector(server,
				new HttpConnectionFactory(httpConfig));
		httpConnector.setPort(serverPort);
		httpConnector.setIdleTimeout(config.getIdleTimeout());
		server.addConnector(httpConnector);

		HandlerCollection handlers = new HandlerCollection();
		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
		context.setContextPath("/");
		
	    APMsgServlet apserch = new APMsgServlet();
	    context.addServlet(new ServletHolder(apserch), AgentUrl.APPROPERTY);
	    context.addServlet(new ServletHolder(apserch), AgentUrl.APLOGIN);
	    context.addServlet(new ServletHolder(apserch), AgentUrl.APLOGOUT);
	    context.addServlet(new ServletHolder(apserch), AgentUrl.APSEARCH);
	    context.addServlet(new ServletHolder(apserch), AgentUrl.STASEARCH);
	    context.addServlet(new ServletHolder(apserch), AgentUrl.APAGGR);
	    context.addServlet(new ServletHolder(apserch), AgentUrl.STAAGGR);
	    context.addServlet(new ServletHolder(apserch), AgentUrl.CUSTOMAGGR);
	    context.addServlet(new ServletHolder(apserch), AgentUrl.CUSTOMTYPEAGGR);

		handlers.addHandler(context);
		server.setHandler(handlers);

		// request log
		NCSARequestLog requestLog = new NCSARequestLog();
		requestLog.setFilename(logName);
		requestLog.setRetainDays(config.getRetainDays());
		requestLog.setLogTimeZone(config.getRequestLogTimezone());
		requestLog.setLogDateFormat(config.getRequestLogDateFormat());
		requestLog.setAppend(true);
		requestLog.setExtended(true);
		RequestLogHandler handlerReqLog = new RequestLogHandler();
		handlerReqLog.setRequestLog(requestLog);
		handlers.addHandler(handlerReqLog);

		try {
			server.start();
		} catch (Exception e) {
			LOG.error("server exception! - " + e.getMessage());
		}
	}
	
	public void run(){
	    LOG.info("start http gather server ...");
	    if(config.isMujob_on()){
	  		int mujob_httpport = config.getMujob_httpPort();
			String mujob_logname = config.getMujob_logName();
			String mujob_index = config.getMujob_IndexName();
			String mujob_type = config.getMujob_IndexType();
			String mojub_ctrlURL = "http://" + config.getMujob_ctrlIp() + ":" + config.getMujob_ctrlPort();
			String mujob_skURL = "http://" + config.getMujob_skValidIp() + ":" + config.getMujob_skValidPort()+ "/es/validatesession?";
			
	    	createActiveServer(mujob_httpport, mujob_logname, mujob_index, mujob_type, mojub_ctrlURL, mujob_skURL);
	    }
	      
	    if(config.isNetcenter_on()){
	    	int nc_httpport = config.getNc_httpPort();
			String nc_logname = config.getNc_logName();
			String nc_index = config.getNc_IndexName();
			String nc_type = config.getNc_IndexType();
			String nc_ctrlURL = "http://" + config.getNc_ctrlIp() + ":"+ config.getNc_ctrlPort();
			String nc_skURL = "http://" + config.getNc_skValidIp() + ":"+ config.getNc_skValidPort() + "/es/validatesession?";
			createActiveServer(nc_httpport, nc_logname, nc_index, nc_type,nc_ctrlURL, nc_skURL);
	    }
	      
	    if(config.isAp_on()){
	    	int ap_httpport = config.getAp_httpPort();
			String ap_logname = config.getAp_logName();
	    	createApServer(ap_httpport, ap_logname);
	    }
	}
//	public void run()
//	{    

      
/*      QueuedThreadPool threadPool = new QueuedThreadPool(config.getMaxThreadNumOfQueue(), config.getMinThreadNumOfQueue());
      Server server = new Server(threadPool);
          
      HttpConfiguration httpConfig = new HttpConfiguration();
      httpConfig.setSecureScheme("https");  
      
      ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
      httpConnector.setPort(serverPort);
      httpConnector.setIdleTimeout(config.getIdleTimeout());
      server.addConnector(httpConnector);
      
      //处理探针请求
//      HandlerCollection handlers = new HandlerCollection();      
//      ServletHandler handler = new ServletHandler();   
//      handler.addServletWithMapping(HttpGatherServlet.class, AgentUrl.PROBETASK);
//      //web检索服务
//      handler.addServletWithMapping(SearchFromESServlet.class, AgentUrl.WebToES);
//      //老手机的检索接口
//      handler.addServletWithMapping(SearchFromESServlet.class, AgentUrl.MOBILE_SEARCH);
//      //手机检索服务
//      handler.addServletWithMapping(ModeSearchServlet.class, AgentUrl.TEMPLATE_SEARCH);
//      handlers.addHandler(handler);
//      server.setHandler(handlers);
      
      
      HandlerCollection handlers = new HandlerCollection();
      ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
      context.setContextPath("/");
      context.addServlet(new ServletHolder(new HttpGatherServlet(skurl, queue)), AgentUrl.PROBETASK);
      HttpServlet simpleSearch = new SearchFromESServlet(cindex, ctype);
      context.addServlet(new ServletHolder(simpleSearch), AgentUrl.WebToES);
      context.addServlet(new ServletHolder(simpleSearch), AgentUrl.MOBILE_SEARCH);
      context.addServlet(new ServletHolder(new ModeSearchServlet(cindex, ctype)), AgentUrl.TEMPLATE_SEARCH);
      if((config.getMujob_httpPort() == serverPort)){
	      APMsgServlet apserch = new APMsgServlet();
	      context.addServlet(new ServletHolder(apserch), AgentUrl.APLOGIN);
	      context.addServlet(new ServletHolder(apserch), AgentUrl.APLOGOUT);
	      context.addServlet(new ServletHolder(apserch), AgentUrl.APSEARCH);
	      context.addServlet(new ServletHolder(apserch), AgentUrl.STASEARCH);
      }
      handlers.addHandler(context);
      server.setHandler(handlers);
      
      // request log
      NCSARequestLog requestLog = new NCSARequestLog();
      requestLog.setFilename(logName);
      requestLog.setRetainDays(config.getRetainDays());
      requestLog.setLogTimeZone(config.getRequestLogTimezone());
      requestLog.setLogDateFormat(config.getRequestLogDateFormat());
      requestLog.setAppend(true);
      requestLog.setExtended(true);
      RequestLogHandler handlerReqLog = new RequestLogHandler();
      handlerReqLog.setRequestLog(requestLog);
      handlers.addHandler(handlerReqLog);
      
      try
      {
          server.start();
          server.join();
      }
      catch (Exception e)
      {
          LOG.error("server exception! - " + e.getMessage());
      }*/
//	}
}
